﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net;
using System.ServiceModel.Syndication;
using System.Windows.Browser;
using System.Windows.Input;
using System.Xml;
using System.Windows;
using System.Collections.ObjectModel;
using ZFCNew.Code;
using System.Linq;

namespace ZFCNew.ViewModels
{
    public class FeedReaderModel : INotifyPropertyChanged
    {
        private const int PageSize = 4;
        private const string PipeUrl = "http://pipes.yahooapis.com/pipes/pipe.run?_id=4rBri9Ef3RG8CEGLLe2fWQ&_render=rss&feedUrl=";
        private int _currentPage = 0;
        private int _totalPage = 0;

        public bool CanGoNext
        {
            get { return _currentPage < _totalPage; }
        }
        public bool CanGoPrev
        {
            get { return _currentPage > 0; }
        }

        private List<SyndicationItem> _itemColl;
        public ICommand GetNextResultSetCommand { get; private set; }
        public ICommand GetPreviousResultSetCommand { get; private set; }

        public ObservableCollection<SyndicationItem> CurrentColl { get; private set; }


        public FeedReaderModel()
        {
            CurrentColl = new ObservableCollection<SyndicationItem>();
            GetNextResultSetCommand = new DelegateCommand(GoNext, (s) => true);
            GetPreviousResultSetCommand = new DelegateCommand(GoPrevious, (s) => true);
        }

        private void GoNext(object s)
        {
            if (CanGoNext)
            {
                _currentPage++;
                AdjustPages();
            }
        }

        private void AdjustPages()
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
                                                          {
                                                              CurrentColl.Clear();
                                                              var newList =
                                                                  _itemColl.Skip(_currentPage*PageSize).Take(PageSize);
                                                              foreach (var item in newList)
                                                              {
                                                                  CurrentColl.Add(item);
                                                              }
                                                              NotifyPropertyChanged("CanGoNext", "CanGoPrev");
                                                          });
        }

        private void GoPrevious(object s)
        {
            if (CanGoPrev)
            {
                _currentPage--;
                AdjustPages();
            }
        }
        public void DownloadFeed(string feedUri)
        {
            Deployment.Current.Dispatcher.BeginInvoke(()=>News.Loaer.Visibility = Visibility.Visible);
            string url = string.Concat(PipeUrl, HttpUtility.UrlEncode(feedUri));
            var request = (HttpWebRequest)WebRequest.Create(new Uri(url));
            request.BeginGetResponse(ResponseHandler, request);
        }

        private void ResponseHandler(IAsyncResult asyncResult)
        {
            var request = (HttpWebRequest)asyncResult.AsyncState;
            var response = (HttpWebResponse)request.EndGetResponse(asyncResult);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                XmlReader reader = XmlReader.Create(response.GetResponseStream());
                var feed = SyndicationFeed.Load(reader);
                _itemColl = feed.Items.ToList();
                _totalPage =(int) Math.Ceiling(((double)_itemColl.Count) / PageSize) - 1;
                AdjustPages();
                Deployment.Current.Dispatcher.BeginInvoke(()=> News.Loaer.Visibility = Visibility.Collapsed);

            }
        }

        #region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(params String[] info)
        {
            if (PropertyChanged != null)
            {
                foreach (var s in info)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(s));
                }

            }
        }

        #endregion


    }
}